package com.example.sls.controller;

import com.example.sls.pojo.Constants;
import com.example.sls.utils.LogUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 编者：蓝江富
 * 时间：2024/6/18 7:53
 * 当浏览器访问对应链接时，会渲染本地图片
 */
@RestController
@RequestMapping("img")
public class ImgManager {

  final String srcPath = Constants.IMG_PATH;

  // 用户头像，数据库中保存的用户头像信息为文件名称。
  @GetMapping("user/{imgName}")
  public ResponseEntity<byte[]> getUserImg(@PathVariable String imgName,HttpServletResponse response) throws IOException {
    Path imgPath = Paths.get(srcPath + "user/" + imgName);
    try {
      byte[] imgBytes = Files.readAllBytes(imgPath);
      return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(imgBytes);
    } catch (IOException e) {
      LogUtil.err(imgPath + "文件不存在");
    }
    return null;
  }
}
